'use client';

import type { IMenu, ISubmenu } from '@/interfaces';
import {
  type Dispatch,
  type MouseEvent,
  type SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react';
import classNames from 'classnames';
import { useRouter, useSelectedLayoutSegments } from 'next/navigation';

export default function Menus(
  this: any,
  { items }: { items: IMenu[] | ISubmenu[] },
) {
  const [currentItem, setCurrentItem] = useState<IMenu | ISubmenu>();
  const selectedLayoutSegments = useSelectedLayoutSegments();
  const segment = (
    selectedLayoutSegments.length > 2
      ? [selectedLayoutSegments[0], selectedLayoutSegments[1]]
      : selectedLayoutSegments
  ).join('/');

  useEffect(() => {
    let find: IMenu | ISubmenu | undefined = (items as IMenu[]).find((item) =>
      item.path.includes(segment),
    );
    if (!find) {
      find = (items as IMenu[]).find((item) =>
        item.submenus.find((submenu) => submenu.path.includes(segment)),
      );

      if (find && (find as IMenu).submenus.length > 0) {
        find = (find as IMenu).submenus.find((item) =>
          item.path.includes(segment),
        );
      }
    }

    setCurrentItem(find || items[0]);
  }, []);

  return (
    <Ul
      items={items}
      currentItem={currentItem}
      setCurrentItem={setCurrentItem}
      ulClass="animate__bounceInLeft"
    />
  );
}

const Ul = ({
  items,
  currentItem,
  setCurrentItem,
  ulClass,
  liClass,
}: {
  items: IMenu[] | ISubmenu[];
  currentItem: IMenu | ISubmenu | undefined;
  setCurrentItem: Dispatch<SetStateAction<IMenu | ISubmenu | undefined>>;
  ulClass?: string;
  liClass?: string;
}) => {
  return (
    <ul
      className={classNames(
        'list-group list-group-flush user-select-none animate__animated',
        ulClass,
      )}
    >
      {items.map((item, index) => {
        return (
          <Li
            key={item.id}
            item={item}
            currentItem={currentItem}
            setCurrentItem={setCurrentItem}
            liClass={liClass}
            index={(index + 1) / 3}
          />
        );
      })}
    </ul>
  );
};

const Li = ({
  item,
  currentItem,
  setCurrentItem,
  liClass,
  index,
}: {
  item: IMenu | ISubmenu;
  currentItem: IMenu | ISubmenu | undefined;
  setCurrentItem: Dispatch<SetStateAction<IMenu | ISubmenu | undefined>>;
  liClass?: string;
  index?: number;
}) => {
  const [hideSubmenus, setHideSubmenus] = useState(true);
  const liRef = useRef<HTMLLIElement>(null);
  const router = useRouter();

  useEffect(() => {
    const element = liRef.current;
    if (element) {
      element.style.setProperty('--animate-duration', `${index ?? 1}s`);
    }
  }, []);

  function onClickItem(item: IMenu | ISubmenu, e: MouseEvent<HTMLLIElement>) {
    if (item.type === 2) {
      e.stopPropagation();
      e.preventDefault();
      setCurrentItem(item);
      menuTypeProcessing(item);
      return;
    }

    if (item.type === 1 && (item as IMenu).submenus.length > 0) {
      setHideSubmenus(!hideSubmenus);
    } else {
      setCurrentItem(item);
      menuTypeProcessing(item);
    }
  }

  function menuTypeProcessing(item: IMenu | ISubmenu) {
    if (item.menuType === 'LINK') {
      router.push(item.path);
    }
  }

  return (
    <li
      ref={liRef}
      className={classNames(
        'list-group-item list-group-item-action cursor-pointer rounded-4 animate__animated',
        {
          active:
            (currentItem && currentItem.id === item.id) ||
            (hideSubmenus &&
              item.type === 1 &&
              currentItem &&
              (item as IMenu).submenus.some(
                (value) => value.id === currentItem.id,
              )),
        },
        liClass,
      )}
      aria-current="true"
      onClick={onClickItem.bind(this, item)}
    >
      <div className="row">
        <div className="col-auto align-self-center">
          <div
            className="rounded-4 d-flex align-items-center justify-content-center bg-body-tertiary ms-auto"
            style={{ width: 48, height: 48 }}
          >
            <i className="bi bi-list fs-4 text-secondary"></i>
          </div>
        </div>
        <div className="col align-self-center">
          {!hideSubmenus &&
          item.type === 1 &&
          (item as IMenu).submenus.length > 0 ? (
            <Ul
              items={(item as IMenu).submenus}
              currentItem={currentItem}
              setCurrentItem={setCurrentItem}
              liClass="animate__bounceInLeft"
            />
          ) : (
            <div className="">{item.name}</div>
          )}
        </div>

        {item.type === 1 && (item as IMenu).submenus.length > 0 && (
          <div className="col-auto align-self-center">
            <i className="bi bi-chevron-down fs-4"></i>
          </div>
        )}
      </div>
    </li>
  );
};
